import 'package:flutter/material.dart';
import 'package:home_framework/mock/goods_mock_data.dart';
import 'package:home_framework/models/goods_entity.dart';
import 'package:home_framework/pages/state_demo/goods_item.dart';
import 'package:home_framework/states/cart_model.dart';
import 'package:provider/provider.dart';
import '../../routers/fluro_router.dart';

class GoodsListPage extends StatelessWidget {
  const GoodsListPage({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    List<Map<String, dynamic>> mockGoods = GoodsMockData.list(1, 20);
    List<GoodsEntity> goods =
        mockGoods.map((item) => GoodsEntity.fromJson(item)).toList();
    return Scaffold(
      appBar: AppBar(
        title: Text('商品列表'),
        actions: [
          IconButton(
              icon: Icon(Icons.shopping_cart),
              onPressed: () {
                RouterManager.router
                    .navigateTo(context, RouterManager.cartPath);
              }),
        ],
      ),
      body: Consumer<CartModel>(
        builder: (context, cart, child) {
          return ListView.builder(
              itemBuilder: (BuildContext context, int index) {
            GoodsEntity goodsEntity = goods[index];
            bool isInCart = context.read<CartModel>().isInCart(goodsEntity);
            return Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Expanded(child: GoodsItem(goodsEntity)),
                TextButton(
                  onPressed: isInCart
                      ? null
                      : () {
                          var cart = context.read<CartModel>();
                          cart.add(goodsEntity);
                        },
                  child: isInCart
                      ? const Icon(Icons.check, semanticLabel: 'ADDED')
                      : const Text('ADD'),
                  style: ButtonStyle(
                    overlayColor:
                        MaterialStateProperty.resolveWith<Color>((states) {
                      if (states.contains(MaterialState.pressed)) {
                        return Theme.of(context).primaryColor;
                      }
                      return null; // Defer to the widget's default.
                    }),
                  ),
                )
              ],
            );
          });
        },
      ),
    );
  }
}
